using JEngine.Framework;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class PEDGroupCell : MonoBehaviour
{
    public int GroupID;
    public bool isOn;
    public bool isCheckOne;

    public class CallEvent : UnityEvent<bool>
    {
    }

    public CallEvent onValueChanged = new CallEvent();

    void Awake()
    {
        PEDButtonGroup.Instance.AddInfo(GroupID, gameObject);
    }

    private void Start()
    {
        if (GetComponent<Button>())
        {
            GetComponent<Button>().AddClick(OnBtnClick);
        }
    }

    public void OnBtnClick(GameObject obj)
    {
        PEDGroupCell cell = obj.GetComponent<PEDGroupCell>();
        if (!PEDButtonGroup.Instance.lastBtn.ContainsKey(GroupID))
        {
            PEDButtonGroup.Instance.lastBtn.Add(GroupID, obj);
        }

        if (PEDButtonGroup.Instance.lastBtn[GroupID] == obj)
        {
            if (cell.isCheckOne && cell.isOn)
                return;
            cell.isOn = !cell.isOn;
            cell.onValueChanged?.Invoke(cell.isOn);
        }
        else
        {
            PEDButtonGroup.Instance.lastBtn[GroupID].GetComponent<PEDGroupCell>().isOn = false;
            PEDButtonGroup.Instance.lastBtn[GroupID].GetComponent<PEDGroupCell>().onValueChanged
                ?.Invoke(false);


            cell.isOn = true;
            cell.onValueChanged?.Invoke(cell.isOn);
        }

        PEDButtonGroup.Instance.lastBtn[GroupID] = obj;
    }
}

public class PEDButtonGroup
{
    private Dictionary<int, List<GameObject>> _dictionary = new Dictionary<int, List<GameObject>>();
    private static PEDButtonGroup _instance = null;
    public Dictionary<int, GameObject> lastBtn = new Dictionary<int, GameObject>();

    public static PEDButtonGroup Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new PEDButtonGroup();
            }

            return _instance;
        }
        //set { _instance = value; }
    }

    public void AddInfo(int groupID, GameObject gameObject)
    {
        if (_dictionary.ContainsKey(groupID))
        {
            _dictionary[groupID].Add(gameObject);
        }
        else
        {
            _dictionary.Add(groupID, new List<GameObject> {gameObject});
        }
    }

    public void ClearByID(int id)
    {
        if (_dictionary.ContainsKey(id))
        {
            _dictionary.Remove(id);
        }

        if (lastBtn.ContainsKey(id))
        {
            lastBtn.Remove(id);
        }
    }

    public List<GameObject> GetListByID(int id)
    {
        List<GameObject> g = null;
        _dictionary.TryGetValue(id, out g);
        if (g != null)
        {
            foreach (var VARIABLE in g)
            {
                VARIABLE.GetComponent<PEDGroupCell>().isOn = false;
            }
        }

        return g;
    }

    
}